//package wmmd.disc.webmaster;

import java.io.*;
import java.text.SimpleDateFormat;
import java.sql.*;
import java.util.Calendar;
import javax.servlet.*;
import javax.servlet.http.*;
import db.DatabaseConnector;

public class ChronoList extends HttpServlet {
    
    //----------------------------------------------------------------------------------------
    /**
     * Called by Rl.jsp; chronologically lists all messages posted after a specified time period
     */
    
    public String setDate(int index) {
        //Function returns the date in yyyy-MM-dd format required by jdbc.
        //Set the starting date as follows:
        //0=last 3 months, 1=last year  2=last 6 month, 3=last month, 4=last week, 5=last day, 6=last 3 days
        
        Calendar rightnow = Calendar.getInstance();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        
        if (index == 0) {
            rightnow.add(Calendar.MONTH, -3);
        } else if (index == 1) {
            rightnow.add(Calendar.YEAR, -1);
        } else if (index == 2) {
            rightnow.add(Calendar.MONTH, -6);
        } else if (index == 3) {
            rightnow.add(Calendar.MONTH, -1);
        } else if (index == 4) {
            rightnow.add(Calendar.DATE, -7);
        } else if (index == 5) {
            rightnow.add(Calendar.DATE, -1);
        } else if (index == 6) {
            rightnow.add(Calendar.DATE, -3);
        }
        
        return dateFormat.format(rightnow.getTime());
    }
    
    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        
        //The JSP document passes in which db table to use
        String tablename = request.getParameter("tName");
        
        // Variables for date strings
        SimpleDateFormat fullDate = new SimpleDateFormat("M/dd/yy 'at' hh:mm a");
        int TimeSpan = 0;
        
        //Variables for the database connection
        DatabaseConnector con1 = null;
        DatabaseConnector con2 = null;
        ResultSet rs1 = null;
        ResultSet rs2 = null;
        
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        
        try {
            con1 = new DatabaseConnector(DatabaseConnector.getDatabaseType());
            con2 = new DatabaseConnector(DatabaseConnector.getDatabaseType());
            
            //Get the index for the starting date as follows:
            //0=last 3 months, 1=last year, 2=last 6 months, 3=last month, 4=last week
            if(request.getParameter("RDate")!=null) {
                TimeSpan = 0 + Integer.valueOf(request.getParameter("RDate")).intValue();
            } else {
                TimeSpan = 0 + Integer.valueOf(request.getParameter("adate_default")).intValue();
            }
            
            //Using setDate to set the start date based on the selected index
            String StartDate = setDate(TimeSpan);
            
            //Writes date to page
            out.println(" <strong>" + StartDate + "</strong></p>");
            out.println("<div style=\"margin-left: 0.5in\">");
            
            //Get all the main topics in reverse order -- implying most recent topic first
            String SQL = "SELECT ID,Topic,TLevel,Name,Date,Subject FROM " + tablename + " WHERE Topic > 0 AND ResponseID = Topic AND Date >= ? ORDER BY ResponseID Desc";
            rs1 = con1.selectSQL_RS(SQL, new Object[]{StartDate});
            
            //Display the topic and all responses in reverse chronological order
            int NumTopics = 0;

            if(rs1 != null)
            {
                while(rs1.next()) {
                    //Store date, topic, and ID as strings
                    String id_string = rs1.getString("ID");
                    String topic_string = rs1.getString("Topic");
                    String tlevel_string = rs1.getString("TLevel");
                    String nameStr = rs1.getString("Name");
                    Timestamp timeStamp = rs1.getTimestamp("Date");
                    String subject1_string = rs1.getString("Subject");
                
                    // Format the date and username for the screen
                    String dateStr = fullDate.format(timeStamp);
                    //nameStr = nameStr.substring(0, nameStr.length()-2);
                
                    // Display the main topic
                    NumTopics = NumTopics + 1;
                    out.println("<div class=\"disctopic\"><a href=\"OneTopic.jsp?RTT=" + topic_string + "\">");
                    out.print(topic_string + ".</a>  <a href=\"displaymessage.jsp?RTID=" + id_string + "\">");
                    out.print(subject1_string + "</a> by " + nameStr);
                    out.println(" on " + dateStr + "</div>");
                
                    //Get all the subtopics of the main topic
                    SQL = "SELECT ID,TLevel,Name,Date,Subject FROM " + tablename + " WHERE Topic = ? AND ID <> ?  ORDER BY ResponseID";
                    rs2 = con2.selectSQL_RS(SQL, new Object[]{topic_string,id_string});
                
                    //Display the subtopics of the main topic, keeping track of level
                    int CurrLevel = Integer.valueOf(tlevel_string).intValue();
                    int ELevels = 0;
                    int jIndex = 0;

                    if(rs2 != null)
                    {
                        while(rs2.next()) {
                            String id2_string = rs2.getString("ID");
                            String tlevel2_string = rs2.getString("TLevel");
                            String nameStr2 = rs2.getString("Name");
                            Timestamp timeStamp2 = rs2.getTimestamp("Date");
                            String subject2_string = rs2.getString("Subject");
                    
                            //If subject is longer than 50 chars, cut it down so it fits into the db
                            if(subject2_string.length() > 50) {
                                subject2_string = subject2_string.substring(0, 50);
                            }
                    
                            // Format the date and username for the screen
                            String dateStr2 = fullDate.format(timeStamp2);
                            //nameStr2 = nameStr2.substring(0, nameStr2.length()-2);
                    
                            //If the current message's topic level is the same as the previous one,
                            //display it accordingly.
                            int CurrLevel2 = Integer.valueOf(tlevel2_string).intValue();
                    
                            if(CurrLevel2 == CurrLevel) {
                                out.println("<li><a href =\"displaymessage.jsp?RTID=" + id2_string + "\">");
                                out.print(nameStr2 + " posted " + subject2_string + "</a>");
                                out.print("&nbsp;(" + dateStr2 + ")");
                            }
                            //If the current message's topic level is greater than the previous one,
                            //start a new <UL> level.
                            else if (CurrLevel2 > CurrLevel) {
                                out.println("\n<ul>");
                                ELevels = ELevels + 1;
                                out.println("<li><a href=\"displaymessage.jsp?RTID=" + id2_string + "\">");
                                out.print(nameStr2 + " posted " + subject2_string + "</a>");
                                out.print("&nbsp;(" + dateStr2 + ")");
                                CurrLevel = CurrLevel2;
                            } else {
                                //Return the UL list to the main level
                                for(jIndex=(CurrLevel2 + 1); jIndex==CurrLevel; jIndex++) {
                                    out.println("</li>");
                                    out.println("</ul>");
                                    ELevels = ELevels - 1;
                                }
                                out.println("<li><a href =\"displaymessage.jsp?RTID=" + id2_string + "\">");
                                out.print(nameStr2 + " posted " + subject2_string + "</a>");
                                out.print("&nbsp;(" + dateStr2 + ")");
                                CurrLevel = CurrLevel2;
                            }
                        }
                    rs2.close();
                    }
                
                    //Return the UL list to the main level
                    while(ELevels > 0) {
                        out.println("</li>");
                        out.println("</ul>");
                        ELevels = ELevels - 1;
                    }
                }
                rs1.close();
            }
            //No messages posted since start date
            if(NumTopics == 0) {
                out.println("<p><em>There have been no Topics Posted since " + StartDate + "</em></p>");
            }
            out.println("</div>");
        } catch (SQLException e) {
            out.println("SQLException caught in ChronoList: " + e.getMessage());
        } finally {
            try {
                if (rs1 != null) {rs1.close();}
                if(con1 != null) con1.CleanUp();;
                if (rs2 != null) {rs2.close();}
                if(con2 != null) con2.CleanUp();
            } catch (SQLException ignored) {}
        }
    }
}
